package com.up1234567.unistarcloud.demo.web;

import com.up1234567.unistar.common.exception.UnistarLimitException;
import com.up1234567.unistarcloud.demo.web.remote.IMicroApi;
import lombok.CustomLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@CustomLog(topic = "WebController")
@RestController
public class IndexController {

    @Autowired
    private IMicroApi microApi;

    @Autowired
    @Qualifier("restTemplate")
    protected RestTemplate restTemplate;

    @GetMapping("hello")
    public String hello(@RequestParam("name") String name) {
        log.info("micro call {}", name);
        try {
            String deepcall = microApi.hello(name);
            return "hello micro => " + deepcall;
        } catch (UnistarLimitException e) {
            return "hello micro => limited";
        } catch (Exception e) {
            log.error("error: {}", e.getMessage());
            return "hello micro => error";
        }
    }

    @GetMapping("rest")
    public String rest(@RequestParam("name") String name) {
        log.info("rest call");
        try {
            String rest = restTemplate.getForObject("https://www.up1234567.com?rest=" + name, String.class);
            return "rest micro => " + rest;
        } catch (UnistarLimitException e) {
            return "rest micro => limited";
        } catch (Exception e) {
            log.error("error: {}", e.getMessage());
            return "rest micro => error";
        }
    }

}
